package webClient.ChatEngine;

import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JOptionPane;

import server.Person;
import webClient.UserInterfaceApplet.buddyList;

import communication.BuddyPreferencesRequest;
import communication.BuddyStatusChangedRequest;
import communication.ConfirmNewBuddyRequest;
import communication.ConversationOpenedRequest;
import communication.ErrorRequest;
import communication.ReceiveMessageRequest;
import communication.Request;
import communication.ServerConnection;
import communication.SocketConnection;

public class RequestHandler implements Runnable{
	
	public static ArrayList<ArrayList<String>> data1 = new ArrayList<ArrayList<String>>();

	ServerConnection listener;
		
	public RequestHandler(int port){
		try {
			listener = new ServerConnection(port);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Could not create server socket.");
		}
		System.out.println("Handler was created!");
	}
	
	
	public void handleRequest(Request r){
		if(r instanceof ReceiveMessageRequest){
			ReceiveMessageRequest rmr = (ReceiveMessageRequest) r;
			String id = rmr.getConversationID();
			String sender = rmr.getSender();
			String message = rmr.getMessage();
			buddyList.getInstance().deliverMessage(id, sender, message);
		} else if(r instanceof BuddyPreferencesRequest){
			buddyList.launchBuddyList();
			handleBuddyPrefrences((BuddyPreferencesRequest)r);
		} else if(r instanceof ErrorRequest){
			ErrorRequest req = (ErrorRequest) r;
			JOptionPane.showMessageDialog(buddyList.getInstance(), req.getErrorMessage());
		}else if(r instanceof ConversationOpenedRequest){
			ConversationOpenedRequest req = (ConversationOpenedRequest) r;
			String convID = req.getConvID();
			buddyList.getInstance().createChat(convID);
		}else if(r instanceof BuddyStatusChangedRequest){
			BuddyStatusChangedRequest req = (BuddyStatusChangedRequest) r; 
			
			Person p = new Person(req.getBuddy());
			p.setStatus(req.getStatus());
			buddyList.getInstance().updateStatus(p);
		}else if(r instanceof ConfirmNewBuddyRequest){
			ConfirmNewBuddyRequest req = (ConfirmNewBuddyRequest) r;
			buddyList.getInstance().confirmNewBuddy(req);
		}
		
	}
	
	public void handleBuddyPrefrences(BuddyPreferencesRequest r){
		
		buddyList.getInstance().displayBuddyList(r.getBuddyList());
		Person p = r.getOwner();
		if(p != null){
			buddyList.getInstance().setUser(p.getUsername());
		}
		
	}

	public void run() {
		SocketConnection connection;
		while(true){
			try {
				connection = listener.accept();
				handleRequest(connection.readRequest());
				connection.close();
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("Incoming connection failed.");
			}
			
		}
	}

}
